/**
 * 文件名：WidgetApplicationImpl.java
 *
 * 版本信息：v1.0
 * 日期：2013-6-22
 * Copyright  Corporation 2013 
 * 版权所有
 *
 */

package com.foreveross.bsl.mam.model.application.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.foreveross.bsl.common.utils.bean.BeanHelper;
import com.foreveross.bsl.common.utils.enums.OperatEnum;
import com.foreveross.bsl.common.utils.web.QueryFilter;
import com.foreveross.bsl.common.utils.web.QueryFilter.Operator;
import com.foreveross.bsl.common.utils.web.QuerySpecs;
import com.foreveross.bsl.mam.app.application.AppVersionWidgetVersionApplication;
import com.foreveross.bsl.mam.app.application.vo.AppVersionVo;
import com.foreveross.bsl.mam.app.application.vo.AppVersionWidgetVersionVo;
import com.foreveross.bsl.mam.model.app.domain.AppVersion;
import com.foreveross.bsl.mam.model.application.WidgetApplication;
import com.foreveross.bsl.mam.model.application.WidgetVersionApplication;
import com.foreveross.bsl.mam.model.application.vo.WidgetVO;
import com.foreveross.bsl.mam.model.application.vo.WidgetVersionVO;
import com.foreveross.bsl.mam.model.model.domain.Widget;
import com.foreveross.bsl.mam.model.model.domain.WidgetVersion;
import com.foreveross.bsl.mam.rbac.application.PrivilegeApplication;
import com.foreveross.bsl.mongodb.domain.Entity;
import com.foreveross.bsl.mongodb.repository.DynamicQueryBuilder;

/**
 * 此类描述的是：模块接口实现类
 * 
 * @author: panhm@foreveross.com
 * @version: 2013-6-22 下午2:49:53
 */
@Named("widgetApplication")
public class WidgetApplicationImpl implements WidgetApplication {
	@Inject
	private WidgetVersionApplication widgetVersionApplication;
	@Inject
	private AppVersionWidgetVersionApplication appVersionWidgetVersionApplication;
	@Inject
	private PrivilegeApplication privilegeApplication;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.foreveross.bsl.mam.model.application.WidgetApplication#saveEntity
	 * (com.foreveross.bsl.mam.model.application.vo.WidgetVO)
	 */

	@Override
	public WidgetVO saveEntity(WidgetVO entity) {
		// TODO Auto-generated method stub
		Widget widget = new Widget();
		BeanHelper.copyProperties(widget, entity);
		widget = (Widget) widget.save();
		entity.setId(widget.getId());
		// 保存版本
		WidgetVersionVO versionVo = entity.getwVersion().get(0);
		WidgetVersion wiversion = new WidgetVersion();
		BeanHelper.copyProperties(wiversion, versionVo);

		wiversion.setCreated_at(entity.getCreated_at());
		wiversion.setAvailable(entity.getAvailable());
		wiversion.setModified_at(entity.getModified_at());
		wiversion.setWidget_id(widget.getId());
		wiversion.save();
		return entity;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.foreveross.bsl.mam.model.application.WidgetApplication#updateEntity
	 * (java.lang.String, com.foreveross.bsl.mam.model.application.vo.WidgetVO)
	 */

	@Override
	public WidgetVO updateEntity(String id, WidgetVO entity) {
		// TODO Auto-generated method stub
		Widget widget = new Widget();
		widget = (Widget) widget.findOne(id);
		widget.setIcon_id(entity.getIcon_id());
		widget.setCategory_id(entity.getCategory_id());
		widget.setModified_at(new Date());
		widget.setName(entity.getName());
		widget.setHidden(entity.isHidden());
		widget.setTimeUnit(entity.getTimeUnit());
		widget.setAutoShow(entity.isAutoShow());
		widget.setAutoDownload(entity.isAutoDownload());
		widget.setShowIntervalTime(entity.getShowIntervalTime());
		widget.setSortingWeight(entity.getSortingWeight());
		widget.setDiscription(entity.getDiscription());
		widget.setLocal(entity.getLocal());
		widget.setShowIntervalTime(entity.getShowIntervalTime());
		widget.setTimeUnit(entity.getTimeUnit());
		widget.setAppAuth(entity.isAppAuth());
		widget = (Widget) widget.save();

		BeanHelper.copyProperties(entity, widget);
		return entity;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.foreveross.bsl.mam.model.application.WidgetApplication#deleteEntity
	 * (java.lang.String)
	 */

	@Override
	public void deleteEntity(String id) {
		// TODO Auto-generated method stub
		Widget widget = new Widget();
		List<WidgetVersionVO> list = widgetVersionApplication
				.findByWidgetId(id);
		// 删除版本
		if (list != null && list.size() > 0) {
			for (WidgetVersionVO wversion : list) {
				widgetVersionApplication.deleteEntity(wversion.getId());
			}
		}
		privilegeApplication.deletePrivilegesByWidget(id); // 删除授权的模块
		widget.delete(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.foreveross.bsl.mam.model.application.WidgetApplication#getEntity(
	 * java.lang.String)
	 */

	@Override
	public WidgetVO getEntity(String id) {
		// TODO Auto-generated method stub
		WidgetVO entity = new WidgetVO();
		Widget widget = new Widget();
		widget = (Widget) widget.findOne(id);
		if (widget != null) {
			BeanHelper.copyProperties(entity, widget);
			return entity;
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.foreveross.bsl.mam.model.application.WidgetApplication#findAll()
	 */

	@SuppressWarnings("rawtypes")
	@Override
	public List<WidgetVO> findByCategoryId(String categoryId) {
		// TODO Auto-generated method stub

		Widget widget = new Widget();
		List list = widget.findListByProperty("category_id", OperatEnum.EQ,
				categoryId);
		// Iterable iterable =
		// widget.findListByQuery(Query.query(Criteria.where("category_id").));
		List<WidgetVO> result = new ArrayList<WidgetVO>();
		if (list != null) {
			WidgetVO vo;
			Iterator it = list.iterator();
			while (it.hasNext()) {
				widget = (Widget) it.next();
				vo = new WidgetVO();
				BeanHelper.copyProperties(vo, widget);
				result.add(vo);
			}
		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.foreveross.bsl.mam.model.application.WidgetApplication#findAll()
	 */

	@SuppressWarnings("rawtypes")
	@Override
	public List<WidgetVO> findAll() {
		Widget widget = new Widget();
		List<WidgetVO> result = new ArrayList<WidgetVO>();
		Iterable iterable = widget.findAll();
		if (iterable != null) {
			WidgetVO widgetVO;
			Iterator it = iterable.iterator();
			while (it.hasNext()) {
				widget = (Widget) it.next();
				widgetVO = new WidgetVO();
				BeanHelper.copyProperties(widgetVO, widget);

				// 获取最新的前5个对应的版本
				WidgetVersion wVersion = new WidgetVersion();
				List listVersion = wVersion.findListByQuery(Query.query(
						Criteria.where("widget_id").is(widget.getId())).with(
						new Sort(Direction.DESC, "created_at")));
				List<WidgetVersionVO> resultVersion = new ArrayList<WidgetVersionVO>();
				if (resultVersion != null) {
					WidgetVersionVO versionVO;
					Iterator itVersion = listVersion.iterator();
					while (itVersion.hasNext()) {
						wVersion = (WidgetVersion) itVersion.next();
						versionVO = new WidgetVersionVO();
						BeanHelper.copyProperties(versionVO, wVersion);
						resultVersion.add(versionVO);
					}
					widgetVO.setwVersion(resultVersion);
				}
				result.add(widgetVO);
			}
		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.foreveross.bsl.mam.model.application.WidgetApplication#checkIdentity
	 * (java.lang.String)
	 */

	@SuppressWarnings("unchecked")
	@Override
	public WidgetVO checkIdentity(String identify) {
		// TODO Auto-generated method stub
		Widget widget = new Widget();
		WidgetVO widgetVO = new WidgetVO();
		List<Widget> widgetList = widget.findListByProperty("identify", OperatEnum.EQ, identify);
		if (widgetList != null && widgetList.size() > 0) {
			widget = widgetList.get(0);
			BeanHelper.copyProperties(widgetVO, widget);
			return widgetVO;
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.foreveross.bsl.mam.model.application.WidgetApplication#getWidgetsForRbac
	 * (java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<WidgetVO> getWidgetsForRbac(String appid) {
		// TODO Auto-generated method stub

		List<WidgetVO> resultwidgets = new ArrayList<WidgetVO>();

		List<AppVersionWidgetVersionVo> listAppWidget = new ArrayList<AppVersionWidgetVersionVo>();
		AppVersion appVersion = new AppVersion();
		List<AppVersion> appVersionList = appVersion.findListByProperty(
				"applicationid", OperatEnum.EQ, appid); // 获取应用版本
		if (appVersionList != null) {
			// 遍历应用版本集合
			for (AppVersion appv : appVersionList) {
				// 根据应用版本id查询所关联的模块的版本
				List<AppVersionWidgetVersionVo> versionWidgetVersionList = appVersionWidgetVersionApplication
						.getListByPlatEntity(appv.getPlatformid(),
								appv.getVersion(), appv.getApplicationid());
				if (versionWidgetVersionList != null
						&& versionWidgetVersionList.size() > 0) {
					listAppWidget.addAll(versionWidgetVersionList);
				}
			}

			Widget widget;
			WidgetVO widgetVO;
			Map<String, String> distancWidget = new HashMap<String, String>();
			// 遍历关联模块版本
			for (AppVersionWidgetVersionVo appvw : listAppWidget) {
				// 根据关联的版本id查询出版本信息
				WidgetVersionVO widgetVersionVO = (WidgetVersionVO) widgetVersionApplication
						.widgetVersion(appvw.getWidgetId(),
								appvw.getWidgetVersion());

				if (widgetVersionVO != null) {
					if (!distancWidget.containsKey(widgetVersionVO
							.getWidget_id())) { // 过滤重复的模块,如果模块id不存在，则添加到模块集合里
						distancWidget.put(widgetVersionVO.getWidget_id(),
								widgetVersionVO.getWidget_id());
						widget = new Widget();
						widgetVO = new WidgetVO();
						widget = (Widget) widget.findOne(widgetVersionVO
								.getWidget_id());
						BeanHelper.copyProperties(widgetVO, widget);
						resultwidgets.add(widgetVO);
					}
				}
			}
		}
		return resultwidgets;
	}

	@SuppressWarnings("unchecked")
	@Override
	public WidgetVO checkName(String name) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		Widget widget = new Widget();
		WidgetVO widgetVO = new WidgetVO();
		List<Widget> widgetList = widget.findListByProperty("name",
				OperatEnum.EQ, name);
		if (widgetList != null && widgetList.size() > 0) {
			widget = widgetList.get(0);
			BeanHelper.copyProperties(widgetVO, widget);
			return widgetVO;
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public WidgetVO autoShow() {
		// TODO Auto-generated method stub
		Widget widget = new Widget();
		WidgetVO widgetVO = new WidgetVO();
		List<Widget> widgetList = widget.findListByProperty("autoShow",
				OperatEnum.EQ, true);
		if (widgetList != null && widgetList.size() > 0) {
			widget = widgetList.get(0);
			BeanHelper.copyProperties(widgetVO, widget);
			return widgetVO;
		}
		return null;
	}

	@Override
	public void autoShowSatus(String widgetId) {
		// TODO Auto-generated method stub
		Widget widget = new Widget();
		Widget entity = (Widget) widget.findOne(widgetId);
		if (entity != null) {
			entity.setAutoShow(false);
			entity.save();
		}
	}

	/**
	 * 
	 * 获取所有模块
	 * 
	 * @author lizhifeng
	 */
	@Override
	public List<WidgetVO> getModulars() {
		// TODO Auto-generated method stub
		List<WidgetVO> list = new ArrayList<WidgetVO>();
		Widget widget = new Widget();
		Iterable<Entity> widgets = widget.findAll();
		for (Entity entity : widgets) {
			widget = (Widget) entity;
			WidgetVO widgetVO = new WidgetVO();
			BeanHelper.copyProperties(widgetVO, widget);
			list.add(widgetVO);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<WidgetVO> findByQuery(String categoryId, String name) {
		// TODO Auto-generated method stub
		Widget widget = new Widget();
		List<WidgetVO> list = new ArrayList<WidgetVO>();
		DynamicQueryBuilder byQuerySpecs = new DynamicQueryBuilder();
		List<QueryFilter> filters = new ArrayList<QueryFilter>();
		if (StringUtils.isNotEmpty(categoryId)) {
			QueryFilter filter = new QueryFilter("category_id", Operator.EQ,
					categoryId);
			filters.add(filter);
		}
		if (StringUtils.isNotEmpty(name)) {
			QueryFilter filter = new QueryFilter("name", Operator.LIKE, name);
			filters.add(filter);
		}
		QuerySpecs querySpecs = new QuerySpecs();
		querySpecs.setFilters(filters);
		Query query = byQuerySpecs.byQuerySpecs(querySpecs);
		List<Widget> widgetList = widget.findListByQuery(query);
		if (widgetList != null && widgetList.size() > 0) {
			for (int i = 0; i < widgetList.size(); i++) {
				widget = widgetList.get(i);
				WidgetVO widgetVO = new WidgetVO();
				BeanHelper.copyProperties(widgetVO, widget);
				list.add(widgetVO);
			}
		}
		return list;
	}
}
